
    //VARIABLES
        var map;
        var target_div = document.getElementById('map-canvas');
        var default_position = createPosition(48.820773, 2.255941);// Default to Hitema
        var user_marker;
        var max_km = 20; //Default max km
        var bitch_window_infos = new Array();
        var bitch_direction = new Array();        
        var sexe;
        var age1;
        var age2;
        var bonnet;
        var mensuration;
        var bitch_name;
        var hair_color;
        var capote;
        var taille1;
        var taille2;
        var poids1;
        var poids2;    
    //END VARIABLES
//-----------------------------------------------------------------------------------------------------------------------------------//
    //GOOGLE MAP API
        function getLocalisation(){ //Get your geolocalisation
            if (navigator.geolocation) {
                function success(position) {
                    // Location found, show map with these coordinates
                    drawMap(position.coords.latitude, position.coords.longitude);
                }
                function fail(error) {
                    drawMap(default_position);  // Failed to find location, show default map
                }
                // Find the users current position.  Cache the location for 5 minutes, timeout after 6 seconds
                navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 15000});
            } else {
                drawMap(default_position);  // No geolocation support, show default map
            }
        }
        
        function getLocalisationSearch(){ //Get your geolocalisation
            if (navigator.geolocation) {
                function success(position) {
                    // Location found, show map with these coordinates
                    drawMapSearch(position.coords.latitude, position.coords.longitude);
                }
                function fail(error) {
                    drawMapSearch(default_position);  // Failed to find location, show default map
                }
                // Find the users current position.  Cache the location for 5 minutes, timeout after 6 seconds
                navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 15000});
            } else {
                drawMapSearch(default_position);  // No geolocation support, show default map
            }
        }

        function drawMap(user_latitude, user_longitude) { //Draw the map to the div target_div, centered on user_position
            var map_options = {
                zoom: 10,
                center: createPosition(user_latitude, user_longitude),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            map = new google.maps.Map(target_div, map_options);
            // Add user overlay
            user_marker = addMarker("Vous êtes ici.", createPosition(user_latitude, user_longitude), "vert");
            google.maps.event.addListener(user_marker, 'click', function() {
                clearInfos();
                clearDirection();
            });
            addRadius(user_marker);
            whoreCondition(user_latitude, user_longitude);//Add bitches markers
        }
        
        function drawMapSearch(user_latitude, user_longitude) { //Draw the map to the div target_div, centered on user_position
            var map_options = {
                zoom: 10,
                center: createPosition(user_latitude, user_longitude),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            map = new google.maps.Map(target_div, map_options);
            // Add user overlay
            user_marker = addMarker("Vous êtes ici.", createPosition(user_latitude, user_longitude), "vert");
            google.maps.event.addListener(user_marker, 'click', function() {
                clearInfos();
                clearDirection();
            });
            addRadius(user_marker);
            findWhore(user_latitude, user_longitude);//Add bitches markers
        }

        function addMarker(title, position, icon){ //Add a marker to the map
            var marker = new google.maps.Marker({
                position: position,
                map: map,
                title: title,
                icon: icon+".ico"
            });

            return marker;
        }

        
        function addBitchInfos(user_position, bitch_marker, bitch_id, img_url, name, age, boobs, weight, height, type, positif, negatif){
            var content = "<div id='bitch_"+bitch_id+"'class='bitch_window'><div class='bitch_img'><img src='"+img_url+
                        "' alt='Smiley face' height='100' width='100'/></div>"+
                        "<div class='bitch_infos'><ul><li><b><u>Name :</u></b> "+name+"</li>"+
                        "<li><b><u>Age :</u></b> "+age+" years</li>"+
                        "<li><b><u>Boobs :</u></b> "+boobs+"</li>"+
                        "<li><b><u>Weight :</u></b> "+weight+" kg</li>"+
                        "<li><b><u>Height :</u></b> "+height+" m</li>"+
                        "<li><b><u>Type :</u></b> "+type+"</li>"+
                        "</ul></div><div class='clear'></div><button class='bitch_button'>RESERVER</button>"+
                        "<div><IMG SRC='assets/img/pouce.png' ALT='Plus' onclick='ajoutPlus("+bitch_id+","+positif+")'><span id='positif'>("+positif+")</span>"+
                        "<IMG SRC='assets/img/pouce_baisse.png' ALT='Plus' onclick='ajoutMoins("+bitch_id+","+negatif+")'><span id='negatif'>("+negatif+")"+                        "</div></div>";


            addEventMarker(user_position, bitch_marker, content);   
        }

        function addEventMarker(user_position, bitch_marker, content){
            var infowindow = new google.maps.InfoWindow();

            google.maps.event.addListener(bitch_marker, 'click', function() {
                clearInfos();
                calculateDirection(user_position, bitch_marker, infowindow, content);
                bitch_window_infos.push(infowindow);
            });

            google.maps.event.addListener(infowindow,'closeclick',function(){
                clearDirection();
            });
        }

        function calculateDirection(user_position, bitch_marker, infowindow, content){
            clearDirection();
            var distance;
            var duration;
            var direction = new google.maps.DirectionsRenderer({
                map: map
            });

            var request = {
                origin: user_position,
                destination: createPosition(bitch_marker.position.lat(), bitch_marker.position.lng()),
                travelMode: google.maps.DirectionsTravelMode.DRIVING, // Type de transport
                unitSystem: google.maps.UnitSystem.METRIC
            }

            var directionsService = new google.maps.DirectionsService(); // Service de calcul d'itinéraire

            directionsService.route(request, function(response, status){ // Envoie de la requête pour calculer le parcours
                if(status == google.maps.DirectionsStatus.OK){
                    direction.setOptions({ preserveViewport: true });
                    direction.setDirections(response); // Trace l'itinéraire sur la carte et les différentes étapes du parcours
                    bitch_direction.push(direction);
                    distance = response.routes[0].legs[0].distance.value;
                    duration = response.routes[0].legs[0].duration.value;
                    var hours = parseInt(duration / 3600 ) % 24;
                    var minutes = parseInt( duration / 60 ) % 60;
                    var seconds = duration % 60;

                    var result = (hours < 10 ? "0" + hours : hours) + " h-" + (minutes < 10 ? "0" + minutes : minutes) + " m-" + (seconds  < 10 ? "0" + seconds : seconds)+"s";
                    infowindow.setContent(content+(distance/1000)+" km/"+result);
                    infowindow.open(map,bitch_marker);
                }
            });        
        }

        function addRadius(marker){
            var circle = new google.maps.Circle({
                map: map,
                radius: max_km*1000,
                fillColor: '#AA0000',
                strokeOpacity: 0
            });
            circle.bindTo('center', marker, 'position');
        }

        function clearInfos(){
            $.each(bitch_window_infos, function(index, element){
                element.close(); // Close others opened windows infos
            });
        }

        function clearDirection(){
            $.each(bitch_direction, function(index, element){
                element.set('directions', null);
            });
        }

        function createPosition(latitude, longitude){//Transform a latitude and a longitude into a google object latlng
            return new google.maps.LatLng(latitude, longitude);
        }
    //END GOOGLE MAP API
//-----------------------------------------------------------------------------------------------------------------------------------//
    //AJAX REQUEST
        function whoreCondition(user_latitude, user_longitude){
            $.ajax({
                type: "GET",
                url: "./whoreCondition.php",
                dataType: "json",
                data: {
                    user_latitude: user_latitude,
                    user_longitude: user_longitude,
                    max_km: max_km
                },
                success: function (data){
                    $.each(data, function(index, element){
                        marker = addMarker(element.surnom, createPosition(element.latitude, element.longitude), "rose", element.img_url);
                        
                        addBitchInfos(createPosition(user_latitude, user_longitude), marker, element.id, element.img_url, element.surnom, element.age, element.boobs, element.weight, element.height, element.type, element.positif, element.negatif);
                    });
                },
                fail: function() {
                    alert( "error ajax request");
                }
            });
        }
        
        function findWhore(user_latitude, user_longitude){
            console.log(sexe+age1+age2+poids1+poids2+taille1+taille2+bonnet+mensuration+capote+hair_color);
            $.ajax({
                type: "GET",
                url: "./findWhore.php",
                dataType: "json",
                data: {
                    user_latitude: user_latitude,
                    user_longitude: user_longitude,
                    max_km: max_km,
                    sexe: sexe,
                    age1: age1,
                    age2: age2,
                    poids1: poids1,
                    poids2: poids2,
                    taille1: taille1,
                    taille2: taille2,
                    bonnet : bonnet,
                    mensuration : mensuration,
                    capote : capote,
                    hair_color: hair_color  
                },
                success: function (data){
                    console.log(data);
                    $.each(data, function(index, element){
                        marker = addMarker(element.surnom, createPosition(element.latitude, element.longitude), "rose", element.img_url);
                        addBitchInfos(createPosition(user_latitude, user_longitude), marker, element.id, element.img_url, element.surnom, element.age, element.boobs, element.weight, element.height, element.type, element.positif, element.negatif);
                        
                    });
                },
                fail: function() {
                    alert( "error ajax request");
                }
            });
        }
    //END AJAX REQUEST
//-----------------------------------------------------------------------------------------------------------------------------------//
    //CLICK EVENT
        function clickMap(){
            max_km = $("#rayon_action").val();
            $("#menu").fadeOut();
            $("#recherche").fadeOut();
            $("#new_search").fadeIn();
            $("#map-canvas").css("display","block");
            getLocalisation();
            $('#son')[0].play();
        }
        
        function clickFind(){
            max_km = $("#rayon_action").val();
            sexe = $("#checkbox-v-2a").val(); 
            age1 = $("#age1").val();
            age2= $("#age2").val();
            poids1= $("#poid1").val();
            poids2= $("#poid2").val();
            taille1= $("#taille1").val();
            taille2= $("#taille2").val();
            bonnet= $("#mensuration").val();
            mensuration= $("#mensuration_taille").val();
            capote = $("#slider").val();
            hair_color= $("#cheveux").val();
            
            $("#recherche").fadeOut();
            $("#header").fadeIn();
            $("#map-canvas").css("display","block");
            getLocalisationSearch();
            $("#new_search").fadeIn();
        }
        
        function clickRecherche(){
            setTimeout("location.reload(true);");
        }
        
        function clickCritere(){
            $("#menu").fadeOut();
            $("#recherche").fadeIn();
        }
        function ajoutPlus(id,positif){
            alert("Vous avez voté !");
           $.ajax({
                type: "GET",
                url: "./note_positif.php",
                dataType: "json",
                data: {
                    id:id,
                    positif:positif
                },
                success: function (data){
                    $.each(data, function(index, element){
                    $("#positif").html("("+element.positif+")");
                        
                    });
                },
                fail: function() {
                    alert( "error ajax request");
                }
            });
        }

        function ajoutMoins(id,negatif){
            alert("Vous avez voté !");
           $.ajax({
                type: "GET",
                url: "./note_negatif.php",
                dataType: "json",
                data: {
                    id:id,
                    negatif:negatif
                },
                success: function (data){
                    $.each(data, function(index, element){
                    $("#negatif").html("("+element.negatif+")");
                        
                    });
                },
                fail: function() {
                    alert( "error ajax request");
                }
            });
        }
    //END CLICK EVENT
//-----------------------------------------------------------------------------------------------------------------------------------////--    //DOCUMENT READY EVENT
        $(document).ready(function(){
            $("#recherche").hide();
                
                //Détection du support des fonctionnalités Jquery Mobile
                if($.mobile.gradeA()){
                    console.log("Votre navigateur supporte les fonctionnalité Jquery mobile");
                 }else{
                    alert("Votre navigateur ne supporte pas les fonctionnalité Jquery mobile");
                 }

        });